<?php

/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/5/13 16:52
 */

namespace App\Logic\Goods;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Store\CouponRule;
use Illuminate\Database\Eloquent\Builder;
use App\Models\Store\Coupon;
use App\Models\Store\CouponUser;;
use App\Models\Store\Goods;
use Arr;
use Exception;
use Illuminate\Database\QueryException;

class CouponLogic extends CommLogic
{

    /**
     * @author ChenGuangHui
     * @dateTime 2022-05-17
     * @param  [type] $params
     */
    public function lists($params)
    {
        $query = Coupon::query()
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        } else {
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->get()->toArray();
        return $data;
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-05-17
     * @param  array $where
     * @param  array $pageData
     * @param  array $sortData
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = Coupon::query()
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        } else {
            $query = $query->orderBy('id', 'desc');
        }
        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])->toArray();

        foreach ($data['data'] as &$item) {
        }

        return $data;
    }

    /**
     * @param $params
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function store($params)
    {
        $lockName = 'coupon_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            list($grant_start_time, $grant_end_time) = $params['grant_time'];
            list($effective_start_time, $effective_end_time) = $params['effective_time'];
            $data = array(
                'name' => $params['name'],
                'remark' => $params['remark'] ?? '',
                'type' => $params['type'] ?? 0,
                'coupon_type' => $params['coupon_type'] ?? 1,
                'coupon_amount' => $params['coupon_amount'] ?? 0,
                'full_amount' => $params['full_amount'] ?? 0,
                'grant_start_time' => $grant_start_time,
                'grant_end_time' => $grant_end_time,
                'effective_start_time' => $effective_start_time,
                'effective_end_time' => $effective_end_time,
                'status' => $params['status'] ?? 0,
                'quantity' => $params['quantity'] ?? '',
                'repeat_quantity' => $params['repeat_quantity'] ?? 1,
            );
            $result = Coupon::query()->create($data);
            if ($params['type'] == 1) {
                foreach ($params['goods'] as $item) {
                    $data = array(
                        'rule_type' => 1,
                        'coupon_id' => $result->getQueueableId(),
                        'ref_id' => $item['goods_id']
                    );
                    CouponRule::query()->create($data);
                }
            }
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-05-17
     * @param  [type] $data
     * @param  [type] $id
     */
    public function show($data, $id)
    {
        $data = Coupon::query()->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '优惠券不存在！');
        $coupon = $data->toArray();
        $goods = Goods::query()->whereIn('goods_id', explode(',', $coupon["ref_ids"]))->get();
        foreach ($goods as &$item) {
            $item['goods_thumb'] = Arr::first(array_column(json_decode($item['goods_thumb'], true), 'url'));
        }
        $coupon['goods'] = $goods;
        $coupon['grant_time'] = [$coupon['grant_start_time'], $coupon['grant_end_time']];
        $coupon['effective_time'] = [$coupon['effective_start_time'], $coupon['effective_end_time']];
        return $coupon;
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-05-17
     * @param  [type] $params
     * @param  [type] $id
     */
    public function update($params, $id)
    {
        $lockName = 'coupon_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            list($grant_start_time, $grant_end_time) = $params['grant_time'];
            list($effective_start_time, $effective_end_time) = $params['effective_time'];
            $data = array(
                'name' => $params['name'],
                'type' => $params['type'] ?? 0,
                'coupon_type' => $params['coupon_type'] ?? 1,
                'coupon_amount' => $params['coupon_amount'] ?? 0,
                'full_amount' => $params['full_amount'] ?? 0,
                'grant_start_time' => $grant_start_time,
                'grant_end_time' => $grant_end_time,
                'effective_start_time' => $effective_start_time,
                'effective_end_time' => $effective_end_time,
                'status' => $params['status'] ?? 0,
                'quantity' => $params['quantity'] ?? '',
                'repeat_quantity' => $params['repeat_quantity'] ?? 1,
                'remark' => $params['remark'] ?? '',
            );
            Coupon::query()->where('id', $id)->update($data);
            CouponRule::query()->where('coupon_id', $id)->whereNotIn('ref_id', array_column($params['goods'], 'goods_id'))->delete();
            foreach ($params['goods'] as $item) {
                $rule = CouponRule::query()->where('coupon_id', $id)->where('ref_id', $item['goods_id'])->first();
                if (empty($rule)) {
                    $data = array(
                        'rule_type' => 1,
                        'coupon_id' => $id,
                        'ref_id' => $item['goods_id']
                    );
                    CouponRule::query()->create($data);
                }
            }
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }

        return true;
    }

    /**
     * @author ChenGuangHui
     * @dateTime 2022-05-17
     * @param  [type] $id
     */
    public function destroy($id)
    {
        $data = Coupon::query()->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '优惠券不存在！');
        \DB::beginTransaction();
        try {
            Coupon::query()->where('id', $id)->delete();
            CouponRule::query()->where('coupon_id', $id)->delete();
            $data = array(
                'status' => '-1'
            );
            CouponUser::query()->where('coupon_id', $id)->update($data);
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }

        return true;
    }


    /**
     * 导入分类商品
     *
     * @param [type] $params
     * @return void
     */
    public function import($params)
    {
        $data = Coupon::query()->where('id', $params["coupon_id"])->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        return Coupon::query()->where('id', $params["coupon_id"])->update(["ref_ids" => trim($params["select_ids"], ',')]);
    }
}
